package server;

import jdk.nashorn.internal.parser.JSONParser;
import org.dom4j.Document;
import org.dom4j.DocumentException;
import org.dom4j.Element;
import org.dom4j.io.SAXReader;

import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.MalformedURLException;
import java.net.ServerSocket;
import java.net.Socket;
import java.net.URL;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.concurrent.*;

/**
 * Minicat的主类
 */
public class MyBootstrap {

    /**定义socket监听的端口号*/
    private int port = 8080;

    public int getPort() {
        return port;
    }

    public void setPort(int port) {
        this.port = port;
    }


    /**
     * Minicat启动需要初始化展开的一些操作
     */
    public void start() throws Exception {

        // 加载解析相关的配置，web.xml
        loadInitConfig();


        // 定义一个线程池
        int corePoolSize = 10;
        int maximumPoolSize =50;
        long keepAliveTime = 100L;
        TimeUnit unit = TimeUnit.SECONDS;
        BlockingQueue<Runnable> workQueue = new ArrayBlockingQueue<>(50);
        ThreadFactory threadFactory = Executors.defaultThreadFactory();
        RejectedExecutionHandler handler = new ThreadPoolExecutor.AbortPolicy();


        ThreadPoolExecutor threadPoolExecutor = new ThreadPoolExecutor(
                corePoolSize,
                maximumPoolSize,
                keepAliveTime,
                unit,
                workQueue,
                threadFactory,
                handler
        );

        ServerSocket serverSocket = new ServerSocket(port);
        System.out.println("=====>>>Minicat start on port：" + port);


        System.out.println("=========>>>>>>使用线程池进行多线程改造");
        /*
            多线程改造（使用线程池）
         */
        while(true) {

            Socket socket = serverSocket.accept();
            RequestProcessor requestProcessor = new RequestProcessor(socket,servletMap,appBase);
            //requestProcessor.start();
            threadPoolExecutor.execute(requestProcessor);
        }
    }


    private Map<String,HttpServlet> servletMap = new HashMap<String,HttpServlet>();
    private String appBase ="";

    /**
     * 加载解析web.xml，初始化Servlet
     */
    private void loadServlet(String baseUrl,String baseName){
        String webfile=baseUrl+"//web.xml";
        File file=new File(webfile);
        try {
            SAXReader saxReader = new SAXReader();
            Document document = saxReader.read(file);

            Element rootElement = document.getRootElement();

            List<Element> selectNodes = rootElement.selectNodes("//servlet");
            for (int i = 0; i < selectNodes.size(); i++) {
                Element element =  selectNodes.get(i);
                // <servlet-name>lagou</servlet-name>
                Element servletnameElement = (Element) element.selectSingleNode("servlet-name");
                String servletName = servletnameElement.getStringValue();
                // <servlet-class>server.LagouServlet</servlet-class>
                Element servletclassElement = (Element) element.selectSingleNode("servlet-class");
                String servletClass = servletclassElement.getStringValue();


                // 根据servlet-name的值找到url-pattern
                Element servletMapping = (Element) rootElement.selectSingleNode("/web-app/servlet-mapping[servlet-name='" + servletName + "']");
                // /lagou
                String urlPattern = servletMapping.selectSingleNode("url-pattern").getStringValue();
                if(baseName!=null&&baseName.trim().length()>0){
                    urlPattern="/"+baseName+urlPattern;
                }
                servletMap.put(urlPattern, (HttpServlet) Class.forName(servletClass).newInstance());
            }



        } catch (DocumentException e) {
            e.printStackTrace();
        } catch (IllegalAccessException e) {
            e.printStackTrace();
        } catch (InstantiationException e) {
            e.printStackTrace();
        } catch (ClassNotFoundException e) {
            e.printStackTrace();
        }

    }

    /**
     * 首先加载server.xml文件
     */
    private void loadInitConfig() {
        InputStream resourceAsStream = this.getClass().getClassLoader().getResourceAsStream("server.xml");
        SAXReader saxReader = new SAXReader();

        try {
            Document document = saxReader.read(resourceAsStream);
            Element rootElement = document.getRootElement();
            Element serveiceElement = (Element) rootElement.selectSingleNode("//Service");
            if(serveiceElement!=null){
                Element connectorElement = (Element) serveiceElement.selectSingleNode("Connector");
                String ports=connectorElement.attributeValue("port")+"";
                System.out.println("ports:"+ports);
                if(ports!=null&&ports.trim().length()>0){
                    port=Integer.parseInt(ports);
                }
                Element engineElement = (Element) serveiceElement.selectSingleNode("Engine");
                Element hostElement = (Element) engineElement.selectSingleNode("Host");
                String name=hostElement.attributeValue("name")+"";
                System.out.println("this minicat access url is :"+"http://"+name+":"+port);
                appBase=hostElement.attributeValue("appBase")+"";
                // 输入静态资源文件
                File file = new File(appBase);
                if(file.exists()) {
                    if(file.isDirectory()){
                        File[] rootfiles = file.listFiles();
                        if(rootfiles!=null&&rootfiles.length>0){
                            for (int i=0;i<rootfiles.length;i++){
                                File project = rootfiles[i];
                                if(project.exists()) {
                                    if (project.isDirectory()) {
                                        String baseurl = project.getAbsolutePath();
                                        String basename = project.getName();
                                        System.out.println("baseurl:" + baseurl+",basename:"+basename);
                                        loadServlet(baseurl,basename);
                                    }
                                }
                            }
                        }
                    }
                }
                System.out.println("servletMap:"+  servletMap.get("/demo1/index.html"));
            }

        } catch (DocumentException e) {
            e.printStackTrace();
        }

    }

    /**
     * Minicat 的程序启动入口
     * @param args
     */
    public static void main(String[] args) {
        MyBootstrap bootstrap = new MyBootstrap();
        try {
            // 启动Minicat
            bootstrap.start();
        } catch (IOException e) {
            e.printStackTrace();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}
